﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace PermissionCommon
{
    public class FilesHelper
    {
        public static string GetFiles(string path)
        {
            var root = new DirectoryInfo("/").FullName;
            var fatherPath = "/";
            var dir = new DirectoryInfo(path);
            if (path != "/")
            {
                fatherPath = path.Substring(0, path.LastIndexOf("/"));
                if (string.IsNullOrEmpty(fatherPath))
                {
                    fatherPath = "/";
                }
            }

            // 过滤掉 "ajax", "js", "images", "css", "core", "bin", "lib"文件夹
            string[] dfliter = { "ajax", "js", "images", "css", "core", "bin", "lib" };
            var dirs = dir.GetDirectories()
                .Where(q => !dfliter.Contains(q.Name.ToLower()))
                .Select(q => new { q.Name, FullName = getPath(q.FullName, root), Type = 1 })
                .OrderBy(q => q.Name)
                .ToList();
            // 过滤只带有.html或.aspx得文件符合
            string[] ffliter = { ".html", ".aspx" };
            var files = dir.GetFiles()
                .Where(q => ffliter.Contains(q.Extension.ToLower()))
                .Select(q => new { q.Name, FullName = getPath(q.FullName, root), Type = 1 })
                .OrderBy(q => q.Name)
                .ToList();
            dirs.AddRange(files);
            dirs.Insert(0, new
            {
                Name = "返回上级",
                FullName = fatherPath,
                Type = 1
            });
            return JsonHelper.ToJson(dirs);

        }

        public static string GetFileTitle(string path)
        {
            //if (path.StartsWith("/"))
            //{
            //    path = _context.Server.MapPath(GetPara("path"));
            //}
            var text = File.ReadAllText(path);
            var reg = Regex.Match(text, "<title>([^<]*)</title>", RegexOptions.IgnoreCase | RegexOptions.Multiline);
            var title = "";
            if (reg.Success)
            {
                title = reg.Groups[1].Value;
                if (title.Contains("-"))
                {
                    title = title.Substring(0, title.IndexOf("-"));
                }
                title = title.Replace("管理", "");
            }
            return JsonHelper.ToJson("{\"msg\":"+reg.Success+",\"title\":"+ title +"}");
        }

        /// <summary>
        /// 获取要显示的路径
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="root">根路径</param>
        /// <returns></returns>
        private static string getPath(string path, string root)
        {
            var result = path.Replace(root, "").Replace("\\", "/");

            return "/" + result;
        }
    }
}
